//
//  OrderListTableViewCell.swift
//  ZNZXSuperMarket
//
//  Created by 四川中农 on 2018/8/2.
//  Copyright © 2018年 四川中农. All rights reserved.
//

//typealias OrderAgain = ((NSArray,NSDictionary))->Void
typealias ConfirmPayOrder = ()->Void

import UIKit

class OrderListTableViewCell: UITableViewCell {
    
    @IBOutlet weak var bgView: UIView!
    @IBOutlet weak var orderNum: UILabel!
    @IBOutlet weak var orderStatus: UILabel!
    @IBOutlet weak var firstImg: UIImageView!
    @IBOutlet weak var secondImg: UIImageView!
    @IBOutlet weak var thirdImg: UIImageView!
    @IBOutlet weak var fourthImg: UIImageView!
    @IBOutlet weak var goodsCount: UILabel!
    @IBOutlet weak var priceLabel: UILabel!
    @IBOutlet weak var orderTime: UILabel!
    @IBOutlet weak var leftButton: UIButton!
    @IBOutlet weak var rightButton: UIButton!
    
    var flag = 0 // 0 确认收货 1 取消订单
    
    lazy var alertView : AlertContentView = {
        let view = AlertContentView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: UIScreen.ScreenHeight))
        
        view.backClosure = { [weak self] in
            self?.orderUpate()
        }
        
        UIApplication.shared.keyWindow?.addSubview(view)
        return view
    }()
    
    var model:OrderListModel!
    
    var backClosure:TouchBlock!
    
    var confirmPay:ConfirmPayOrder!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        self.leftButton.setBorder(color: "#f7c201", width: 1)
        self.leftButton.setCornerRadio(radio: 15, isMask: false)
        self.bgView.setCornerRadio(radio: 20, isMask: false)
        self.bgView.setShadow(color: "#000000,", offset: CGSize.init(width: 1.8, height: 1.8), radius: 3, opacity: 0.1)
        self.rightButton.setCornerRadio(radio: 15, isMask: false)
        self.rightButton.setShadow(color: "#f7c201", offset: CGSize.init(width: 0, height: 4), radius: 8, opacity: 0.2)
        self.setImageStyle(imgV: self.firstImg)
        self.setImageStyle(imgV: self.secondImg)
        self.setImageStyle(imgV: self.thirdImg)
        self.setImageStyle(imgV: self.fourthImg)

        self.leftButton.addTarget(self, action: #selector(btnClick(sender:)), for: .touchUpInside)
        self.rightButton.addTarget(self, action: #selector(btnClick(sender:)), for: .touchUpInside)
        
    }
    
    func setImageStyle(imgV:UIImageView){
        imgV.corner(byRoundingCorners: .allCorners, radii: 10)
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    
    func reload(withModel model:OrderListModel){
        self.model = model
        self.orderNum.text = model.number
        for i in 0..<4 {
            let imageV = self.viewWithTag(200 + i) as! UIImageView
            imageV.isHidden = false
            if i < (model.goods?.count)! {
                imageV.my_setImage(url: model.goods![i].img, placeholder: Api.placeHolder.rawValue)
            }else{
                imageV.isHidden = true
            }
        }
        self.goodsCount.text = "共\(model.goods?.count ?? 0)个商品"
        
        let str = "¥" + model.money
        var attribute = NSMutableAttributedString.init(string: str)
        attribute.addAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 11)], range: NSString.init(string: str).range(of: "¥" + model.money))
        attribute = NSMutableAttributedString.init(attributedString: attribute)
        attribute.addAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 17)], range: NSString.init(string: str).range(of: model.money.getPriceInteger()))
        
        attribute = NSMutableAttributedString.init(attributedString: attribute)
        attribute.addAttributes([NSAttributedStringKey.foregroundColor:UIColor.init(hexColor: "#ed4848")], range: NSString.init(string: str).range(of: "¥" + model.money))
        self.priceLabel.attributedText = attribute
        self.orderTime.text = "\(model.createTime)".timeStampToString(timeFormat: "YYYY-MM-dd HH:mm:ss")
        
        self.checkOrderType(model: model)
    }
    
    private func checkOrderType(model:OrderListModel){
        self.leftButton.isHidden = false
        self.rightButton.isHidden = false
        switch model.state {
        case 0:
            // 订单类型 0立即支付 1货到付款
            if model.type == 0 {
                self.leftButton.setTitle("取消订单", for: .normal)
                self.rightButton.setTitle("确认付款", for: .normal)
                self.orderStatus.text = "待支付"
            }else{
                self.leftButton.isHidden = true
                self.rightButton.setTitle("确认付款", for: .normal)
                self.orderStatus.text = "待支付(到付)"
            }
        case 1,2:
            
            self.leftButton.isHidden = true
            if model.state == 2 {
                self.rightButton.setTitle("确认收货", for: .normal)
            }else{
                if model.type == 0 {
                    self.rightButton.isHidden = true
                }else{
                    self.rightButton.isHidden = false
                    self.rightButton.setTitle("取消订单", for: .normal)
                }
                
            }
            if model.type == 0 {
                self.orderStatus.text = "待收货"
            }else{
                self.orderStatus.text = "待收货(到付)"
            }
        case 3:
            self.orderStatus.text = "已完成"
            self.leftButton.isHidden = true
            self.rightButton.setTitle("再来一单", for: .normal)
        case 4:
            self.orderStatus.text = "已取消"
            self.leftButton.isHidden = true
            self.rightButton.setTitle("再来一单", for: .normal)
        default:
            break
        }
    }
    
    @objc func btnClick(sender:UIButton) {
        switch sender.titleLabel?.text! {
        case "取消订单","确认收货":
            var title = "确定要收货吗？"
            if sender.titleLabel?.text != "确认收货" {
                title = "确定要取消订单吗？"
            }
            self.alertView.show(withTitle: title)
            
        case "再来一单":
            
            if self.backClosure != nil {
                self.backClosure()
            }
            
        case "确认付款":
            if self.confirmPay != nil {
                self.confirmPay()
            }
        default:
            break
        }
    }
    
    func orderUpate(){
        PKhud.show()
        HttpRequest.requestData(.post, URLString: Api.orderUpdate.rawValue, parameters: ["id":self.model.id]) { (result) in
            PKhud.hiden()
            if result["msg"] as! String == "success"{
                PKhud.showText(text: "操作成功~")
                Utils.DispatchAfter(after: 0.5, handler: {
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "updateList"), object: nil)
                })
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }

}








